import { login } from '../../utils/api';
import { cacheSet, cacheClear} from '../../utils/cache.js';
const state = {
	token:null,
	name: null,
	mobile:null,
	userId: null
}

const mutations = {
	SET_USERID: (state, userId) => {
		state.userId = userId
	},
	SET_MOBILE:(state,mobile)=>{
		state.mobile=mobile
	},
	SET_NAME: (state, name) => {
		state.name = name
	}
}

const actions = {
	// user login
	loginState({commit}, userInfo) {
		let self=this;
		return new Promise((resolve, reject) => {
			login(userInfo).then(res => {
				//console.log(res);
				let rdata=res.data;
				if (rdata.status == 0) {
					commit('SET_USERID', rdata.data.UserID);
					commit('SET_NAME', rdata.data.UserName);
					commit('SET_MOBILE', rdata.data.Mobile);
					cacheSet('userId',rdata.data.UserID,7);
					cacheSet('userName',rdata.data.UserName,7);
					cacheSet('mobile',rdata.data.Mobile,7);
				}
				resolve(res)
			}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	loginOut({commit}) {
		return new Promise(resolve => {
			commit('SET_USERID', null);
			commit('SET_NAME', null);
			commit('SET_MOBILE', null);
			cacheClear();
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
